package com.copd.controller;

import com.copd.common.ApiResponse;
import com.copd.dto.PatientCreateRequest;
import com.copd.dto.PatientUpdateRequest;
import com.copd.entity.Patient;
import com.copd.service.PatientService;
import com.copd.util.JwtUtil;
import com.copd.util.PatientOperationLogger;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "患者管理接口", description = "患者相关的接口")
@RestController
@RequestMapping("/api/patients")
public class PatientController {

    private static final Logger logger = LoggerFactory.getLogger(PatientController.class);

    @Autowired
    private PatientService patientService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private PatientOperationLogger operationLogger;

    @ApiOperation(value = "查询所有患者列表", notes = "返回分页的患者列表")
    @GetMapping
    public ResponseEntity<?> getPatients(
            @ApiParam(value = "患者姓名", required = false) @RequestParam(required = false) String name,
            @ApiParam(value = "住院号", required = false) @RequestParam(required = false) String hospitalizationNumber,
            @ApiParam(value = "科室", required = false) @RequestParam(required = false) String department,
            @ApiParam(value = "性别", required = false) @RequestParam(required = false) String gender,
            @ApiParam(value = "用户ID", required = false, example = "0") @RequestParam(required = false) Integer userId,
            @ApiParam(value = "页码", defaultValue = "1", example = "1") @RequestParam(defaultValue = "1") int page,
            @ApiParam(value = "每页大小", defaultValue = "10", example = "10") @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {
        
        try {
            // 设置医生ID到请求属性
            setDoctorIdFromRequest(request);
            
            List<Patient> patients = patientService.getAllPatients(
                name,
                hospitalizationNumber,
                department,
                gender,
                userId,
                page,
                size
            );
            
            long total = patientService.getTotalPatients(
                name,
                hospitalizationNumber,
                department,
                gender,
                userId
            );
            
            List<Map<String, Object>> formattedPatients = patients.stream()
                .map(patient -> {
                    Map<String, Object> patientMap = new HashMap<>();
                    patientMap.put("patientId", patient.getPatientId());
                    patientMap.put("userId", patient.getUserId());
                    patientMap.put("name", patient.getName());
                    patientMap.put("gender", patient.getGender());
                    patientMap.put("age", patient.getAge());
                    patientMap.put("department", patient.getDepartment());
                    patientMap.put("hospitalizationNumber", patient.getHospitalizationNumber());
                    return patientMap;
                })
                .collect(Collectors.toList());
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", formattedPatients);
            response.put("total", total);
            response.put("page", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取患者列表失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取患者列表失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }

    @ApiOperation(value = "根据ID获取患者信息", notes = "根据患者ID获取详细信息")
    @GetMapping("/{id}")
    public ResponseEntity<?> getPatient(
            @ApiParam(value = "患者ID", required = true, example = "1") @PathVariable int id, 
            HttpServletRequest request) {
        try {
            // 设置医生ID到请求属性
            setDoctorIdFromRequest(request);
            
            Patient patient = patientService.getPatientById(id);
            if (patient == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "未找到ID为" + id + "的患者");
                return ResponseEntity.notFound().build();
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", patient);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取患者信息失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取患者信息失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }

    @ApiOperation(value = "新增患者", notes = "创建新患者，包含基本信息、诊断记录、检查项目、治疗项目和出院建议")
    @PostMapping
    public ResponseEntity<?> addPatient(@RequestBody PatientCreateRequest request, HttpServletRequest servletRequest) {
        try {
            // 设置医生ID到请求属性
            setDoctorIdFromRequest(servletRequest);
            
            Integer patientId = patientService.createPatient(request);
            // 新增：记录操作日志（带设备信息）
            Integer doctorId = (Integer) servletRequest.getAttribute("doctorId");
            String ipAddress = operationLogger.getIpAddress(servletRequest);
            String deviceInfo = servletRequest.getHeader("User-Agent");
            operationLogger.logPatientCreate(doctorId, patientId, request, ipAddress);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "患者添加成功");
            response.put("patientId", patientId);
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            logger.error("添加患者失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        } catch (Exception e) {
            logger.error("添加患者发生系统错误", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "系统错误，请稍后重试");
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }

    /**
     * 删除患者信息
     * @param patientId 患者ID
     * @return 删除结果
     */
    @DeleteMapping("/{patientId}")
    public ResponseEntity<?> deletePatient(
            @ApiParam(value = "患者ID", required = true, example = "1") @PathVariable Integer patientId, 
            HttpServletRequest request) {
        try {
            // 设置医生ID到请求属性
            setDoctorIdFromRequest(request);
            
            boolean success = patientService.deletePatient(patientId);
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("success", true);
                response.put("message", "患者删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "患者删除失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (RuntimeException e) {
            logger.error("删除患者失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        } catch (Exception e) {
            logger.error("删除患者发生系统错误", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "删除患者时发生错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @GetMapping("/{patientId}/detail")
    @ApiOperation("获取患者详细信息")
    public ResponseEntity<?> getPatientDetail(
            @ApiParam(value = "患者ID", required = true, example = "1") @PathVariable Integer patientId, 
            HttpServletRequest request) {
        try {
            // 设置医生ID到请求属性
            setDoctorIdFromRequest(request);
            Integer doctorId = (Integer) request.getAttribute("doctorId");
            
            // 记录患者查询操作
            operationLogger.logPatientQuery(doctorId, patientId, operationLogger.getIpAddress(request));
            
            Map<String, Object> patientDetail = patientService.getPatientDetail(patientId);
            return ResponseEntity.ok(ApiResponse.success(patientDetail));
        } catch (RuntimeException e) {
            logger.error("获取患者详细信息失败", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        } catch (Exception e) {
            logger.error("获取患者详细信息发生系统错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("获取患者信息失败：" + e.getMessage()));
        }
    }

    @ApiOperation(value = "更新患者信息", notes = "更新患者的诊断记录、检查项目、治疗项目和出院建议")
    @PutMapping("/{patientId}")
    public ResponseEntity<?> updatePatient(
            @ApiParam(value = "患者ID", required = true, example = "1") @PathVariable Integer patientId,
            @ApiParam(value = "更新信息", required = true) @RequestBody PatientUpdateRequest request,
            HttpServletRequest servletRequest) {
        try {
            // 设置医生ID到请求属性
            setDoctorIdFromRequest(servletRequest);
            Integer doctorId = (Integer) servletRequest.getAttribute("doctorId");
            
            request.setPatientId(patientId);
            boolean success = patientService.updatePatient(request);
            
            if (success) {
                // 记录患者更新操作
                String deviceInfo = servletRequest.getHeader("User-Agent");
                operationLogger.logPatientUpdate(doctorId, patientId, request, operationLogger.getIpAddress(servletRequest), deviceInfo);
                
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "患者信息更新成功");
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "患者信息更新失败");
                return ResponseEntity.badRequest().body(errorResponse);
            }
        } catch (IllegalArgumentException e) {
            logger.error("更新患者信息失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        } catch (Exception e) {
            logger.error("更新患者信息发生系统错误", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "系统错误，请稍后重试");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    /**
     * 从请求中获取医生ID并设置到请求属性中
     */
    private void setDoctorIdFromRequest(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                Integer doctorId = jwtUtil.getUserIdFromToken(token);
                request.setAttribute("doctorId", doctorId);
                logger.debug("从Token获取医生ID: {}", doctorId);
            } else {
                logger.debug("未找到有效的Authorization头");
            }
        } catch (Exception e) {
            logger.error("从Token获取医生ID失败", e);
        }
    }
}